/* pages/search/search.js */
const app = getApp();
import Toast from '@vant/weapp/toast/toast';

Page({
    data: {
        keyword: '', // 当前搜索关键词
        debouncedKeyword: '', // 防抖后的关键词，实际用于搜索
        products: [], // 搜索结果
        loading: false, // 是否正在加载（整体加载，包括首次和加载更多）
        firstLoadDone: false, // 首次加载是否完成（用于区分初始加载和空状态）
        finished: false, // 是否已加载所有数据
        error: null, // 加载错误提示
        page: 1, // 当前页码
        limit: 10, // 每页数量
        totalPages: 1, // 总页数
        showEmpty: false, // 是否显示空状态
        searchTimeout: null, // 用于搜索防抖的定时器
    },

    onLoad(options) {
        if (options.keyword) {
            this.setData({
                keyword: options.keyword,
                debouncedKeyword: options.keyword
            });
            this.initSearchAndFetch();
        }
    },

    onKeywordChange(event) {
        const newKeyword = event.detail;
        this.setData({
            keyword: newKeyword,
        });

        if (this.data.searchTimeout) {
            clearTimeout(this.data.searchTimeout);
        }

        if (newKeyword.trim() === '') {
            this.setData({
                products: [],
                showEmpty: false,
                finished: false,
                error: null,
                firstLoadDone: false,
                debouncedKeyword: ''
            });
            return;
        }

        const timeoutId = setTimeout(() => {
            this.setData({ debouncedKeyword: newKeyword.trim() });
            this.initSearchAndFetch();
        }, 500); // 500ms 防抖
        this.setData({ searchTimeout: timeoutId });
    },

    onSearch(event) {
        const keywordToSearch = (event.detail || this.data.keyword).trim();
        if (this.data.searchTimeout) {
            clearTimeout(this.data.searchTimeout);
        }
        this.setData({
            keyword: keywordToSearch, // 更新输入框显示
            debouncedKeyword: keywordToSearch
        });
        if (keywordToSearch === '') {
            this.setData({
                products: [],
                showEmpty: false,
                finished: false,
                error: null,
                firstLoadDone: false,
            });
            return;
        }
        this.initSearchAndFetch();
    },

    onClearSearch() {
        if (this.data.searchTimeout) {
            clearTimeout(this.data.searchTimeout);
        }
        this.setData({
            keyword: '',
            debouncedKeyword: '',
            products: [],
            page: 1,
            finished: false,
            loading: false,
            showEmpty: false,
            error: null,
            firstLoadDone: false,
        });
    },

    onCancelSearch() {
        // wx.navigateBack(); // 或者清空搜索词返回上一页
        this.onClearSearch();
    },

    initSearchAndFetch() {
        this.setData({
            products: [],
            page: 1,
            finished: false,
            loading: false,
            showEmpty: false,
            error: null,
            firstLoadDone: false,
        });
        if (this.data.debouncedKeyword) {
            this.fetchProducts(true);
        }
    },

    async fetchProducts(isRefresh = false) {
        if (this.data.loading || (this.data.finished && !isRefresh)) {
            return;
        }
        if (!this.data.debouncedKeyword) {
            this.setData({
                products: [],
                showEmpty: false,
                loading: false,
                finished: false,
                firstLoadDone: true
            });
            return;
        }

        this.setData({ loading: true, error: null });
        if (isRefresh) {
            this.setData({ page: 1, products: [], finished: false, firstLoadDone: false });
        }

        try {
            const params = {
                keyword: this.data.debouncedKeyword,
                page: this.data.page,
                limit: this.data.limit,
                // TODO: Add other filters like category, price range, condition, sort, order here
            };

            const res = await new Promise((resolve, reject) => {
                wx.request({
                    url: `${app.globalData.baseUrl}/api/products/search`,
                    method: 'GET',
                    data: params,
                    // header: { 'Authorization': 'Bearer ' + wx.getStorageSync('token') } // If auth is needed
                    success: (response) => {
                        resolve(response);
                    },
                    fail: (error) => {
                        reject(error);
                    }
                });
            });

            if (res.statusCode === 200 && res.data.success) {
                const { products: newProducts, total, page, totalPages } = res.data.data;
                const currentProducts = isRefresh ? [] : this.data.products;
                const allProducts = [...currentProducts, ...newProducts];

                this.setData({
                    products: allProducts,
                    page: page + 1, // API returns current page, so next page is page + 1
                    totalPages: totalPages,
                    finished: allProducts.length >= total || page >= totalPages,
                    showEmpty: total === 0,
                });
            } else {
                throw new Error(res.data.message || '搜索失败，请稍后再试');
            }
        } catch (err) {
            console.error('Fetch products error:', err);
            this.setData({
                error: err.message || '网络请求失败，请检查网络连接',
                showEmpty: this.data.products.length === 0, // Show empty if error and no products
            });
            Toast.fail(err.message || '请求失败');
        } finally {
            this.setData({ loading: false, firstLoadDone: true });
        }
    },

    onReachBottom() {
        if (!this.data.loading && !this.data.finished && this.data.firstLoadDone) {
            this.fetchProducts();
        }
    },

    goToProductDetail(event) {
        const productId = event.currentTarget.dataset.id;
        if (productId) {
            wx.navigateTo({
                url: `/pages/product/product?id=${productId}`,
            });
        } else {
            console.warn("Product ID is missing for navigation", event.currentTarget.dataset);
        }
    },
}); 